package com.hbgc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hbgc.mapper.TbSpiderMapper;
import com.hbgc.mapper.TbTaskMapper;
import com.hbgc.mapper.TbTypeMapper;
import com.hbgc.mapper.TbVideoMapper;
import com.hbgc.pojo.TbSpider;
import com.hbgc.pojo.TbTask;
import com.hbgc.pojo.TbType;
import com.hbgc.pojo.TbVideo;
import com.hbgc.service.ITaskService;
import com.hbgc.service.spider.HongNiuYunSpider;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;

@Service
public class TaskServiceImpl implements ITaskService {


    @Autowired
    private TbTaskMapper tbTaskMapper;

    @Autowired
    private TbSpiderMapper tbSpiderMapper;

    @Autowired
    private TbVideoMapper tbVideoMapper;

    @Autowired
    private TbTypeMapper typeMapper;

    @Autowired
    private HongNiuYunSpider hongNiuYunSpider;

    @Override
    public PageInfo queryTbTaskByPage(int pageNow, int pageSize, String taskname) {
        PageHelper.startPage(pageNow, pageSize);
        List<TbTask> tbTasks = tbTaskMapper.selectAllByTaskname(taskname);
        PageInfo pageinfo = new PageInfo<>(tbTasks);
        return pageinfo;
    }

    @Override
    public boolean saveTbTask(TbTask tbTask) {
        return tbTaskMapper.insert(tbTask) > 0 ? true : false;
    }

    @Override
    public boolean updateTbTaskById(TbTask tbtask) {
        return tbTaskMapper.updateByPrimaryKey(tbtask) > 0 ? true : false;
    }

    @Override
    public boolean deleteTbTaskById(Long taskid) {
        return tbTaskMapper.deleteByPrimaryKey(taskid) > 0 ? true : false;
    }

    @Override
    public TbTask getTbTaskById(Long taskid) {
        return tbTaskMapper.selectByPrimaryKey(taskid);
    }

    /**
     * 启动收集功能
     *
     * @param taskid
     * @return
     */
    @Override
    public void startTask(Long taskid) {
        TbTask tbTask = tbTaskMapper.selectByPrimaryKey(taskid);
        Long spiderid = (long) tbTask.getSpiderid();
        TbSpider tbSpider = tbSpiderMapper.selectByPrimaryKey(spiderid);
        String spiderName = tbSpider.getSpidername();
        String spiderpath=tbSpider.getSpiderpath(); //同步文件保存的本地路径
        switch (spiderName) {
            case "红牛资源":
                hongNiuYunSpider.init();
                hongNiuYunSpider.getAllData(spiderpath);
                break;
            case "番茄资源":
                break;
            case "无尽资源":
                break;
            case "北极星资源":
                break;
        }

    }


    @Override
    public void collectToday(Long taskid) {

        TbTask tbTask = tbTaskMapper.selectByPrimaryKey(taskid);
        Long spiderid = (long) tbTask.getSpiderid();
        TbSpider tbSpider = tbSpiderMapper.selectByPrimaryKey(spiderid);
        String spiderName = tbSpider.getSpidername();
        String spiderUrl = tbSpider.getSpiderurl();
        String spiderpath=tbSpider.getSpiderpath(); //同步文件保存的本地路径
        switch (spiderName) {
            case "红牛资源":
                List<String> rows = hongNiuYunSpider.collectToday(spiderpath);
                megerData(rows, spiderUrl);
                break;
            case "番茄资源":
                break;
            case "无尽资源":
                break;
            case "北极星资源":
                break;
        }

    }

    @Override
    public void collectWeek(Long taskid) {
        TbTask tbTask = tbTaskMapper.selectByPrimaryKey(taskid);
        Long spiderid = (long) tbTask.getSpiderid();
        TbSpider tbSpider = tbSpiderMapper.selectByPrimaryKey(spiderid);
        String spiderName = tbSpider.getSpidername();
        String spiderUrl = tbSpider.getSpiderurl();
        String spiderpath=tbSpider.getSpiderpath(); //同步文件保存的本地路径
        switch (spiderName) {
            case "红牛资源":
                List<String> rows = hongNiuYunSpider.collectWeek(spiderpath);
                megerData(rows, spiderUrl);
                break;
            case "番茄资源":
                break;
            case "无尽资源":
                break;
            case "北极星资源":
                break;
        }
    }

    @Override
    public void collectAll(Long taskid) {
        TbTask tbTask = tbTaskMapper.selectByPrimaryKey(taskid);
        Long spiderid = (long) tbTask.getSpiderid();
        TbSpider tbSpider = tbSpiderMapper.selectByPrimaryKey(spiderid);
        String spiderName = tbSpider.getSpidername();
        String spiderUrl = tbSpider.getSpiderurl();
        String spiderpath=tbSpider.getSpiderpath(); //同步文件保存的本地路径
        switch (spiderName) {
            case "红牛资源":
                List<String> rows = hongNiuYunSpider.collectAll(spiderpath);
                megerData(rows, spiderUrl);
                break;
            case "番茄资源":
                break;
            case "无尽资源":
                break;
            case "北极星资源":
                break;
        }
    }


    public void megerData(List<String> rows, String spiderUrl) {


        for (String row : rows) {
            System.out.println(row);
            String[] column = row.split(",");
            String videoName = column[0];
            String[] videoColumn = videoName.split(" ");
            String video1 = videoColumn[0];
            String video2 = videoColumn[1];
            String videoType = column[1];
            String updateTime = column[2];
            String detailUrl = spiderUrl + column[3];
            List<TbVideo> tbVideos = tbVideoMapper.selectAllByVideoname(video1);
            System.out.println(tbVideos);
            if (tbVideos != null && tbVideos.size() > 0) {
                TbVideo tbVideo = tbVideos.get(0);
                String videoname2 = tbVideo.getVideoname2();
                System.out.println(videoname2);
                System.out.println(video2);
                System.out.println(videoname2.equals(video2));
                if (!videoname2.equals(video2)) {
                    updateData(detailUrl, tbVideo,updateTime);
                } else {
                    continue;
                }
            } else {
                //新增数据
                saveData(detailUrl,updateTime);
            }
        }

    }


    public void saveData(String detailUrl,String updateTime) {
        TbVideo video = new TbVideo();
        Document dom = null;
        try {
            dom = Jsoup.parse(new URL(detailUrl), 200 * 1000);
            Element paper = dom.selectFirst(".vodImg > img");
            video.setVideopaper(paper.attr("src"));

            Element videonameElement = dom.selectFirst(".vodh > h2");
            String[] videos = videonameElement.text().split(" ");
            String videoname = "";
            if (videos != null && videos.length > 0) {
                for (String videoOne : videos) {
                    videoname += videoOne + "-";
                }
                videoname = videoname.substring(0, videoname.length() - 1);
            } else {
                videoname = videonameElement.text();
            }
            video.setVideoname(videoname);

            Element videoname2 = dom.selectFirst(".vodh > span");
            video.setVideoname2(videoname2.text());

            Element direct = dom.selectFirst("div.vodinfobox > ul > li:nth-child(2) > span");

            video.setVideodirect(direct.text());
            Element actor = dom.selectFirst("div.vodinfobox > ul > li:nth-child(3) > span");

            video.setVideoactor(actor.text());
            Element videotype = dom.selectFirst("div.vodinfobox > ul > li:nth-child(4) > span");
            List<TbType> typeList = typeMapper.selectAllByTypenameList(videotype.text());
            if (typeList != null && typeList.size() > 0) {
                TbType type = typeList.get(0);
                video.setTypeid(type.getTypeid());
            } else {
                video.setTypeid(36);
            }

            Element videoarea = dom.selectFirst("div.vodinfobox > ul > li:nth-child(5) > span");
            video.setVideoarea(videoarea.text());

            Element videolan = dom.selectFirst("div.vodinfobox > ul > li:nth-child(6) > span");

            video.setVideolan(videolan.text());

            Element videotime = dom.selectFirst("div.vodinfobox > ul > li:nth-child(7) > span");

            video.setVideoage(videotime.text());

            Element videolength = dom.selectFirst("div.vodinfobox > ul > li:nth-child(9) > span");

            video.setVideolength(Integer.parseInt(videolength.text()));

            Element score = dom.selectFirst("div.vodinfobox > ul > li:nth-child(13) > span");

            video.setScore(Double.parseDouble(score.text()));
            Element info = dom.selectFirst(".vodplayinfo");
            video.setVideoinfo(info.text());

            video.setLastmodifytime(updateTime);
            Elements as = dom.select("#play_1 > ul > li >  a:nth-child(2)");
            StringBuffer playurl = new StringBuffer();
            for (Element a : as) {
                playurl.append(a.text() + "\r\n");

            }
            video.setPlayurl(playurl.toString());
            tbVideoMapper.insert(video);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public void updateData(String detailUrl, TbVideo video,String updateTime) {

        Document dom = null;
        try {
            dom = Jsoup.parse(new URL(detailUrl), 200 * 1000);
            Element paper = dom.selectFirst(".vodImg > img");
            video.setVideopaper(paper.attr("src"));

            Element videoname = dom.selectFirst(".vodh > h2");

            video.setVideoname(videoname.text());
            Element videoname2 = dom.selectFirst(".vodh > span");

            video.setVideoname2(videoname2.text());
            Element direct = dom.selectFirst("div.vodinfobox > ul > li:nth-child(2) > span");

            video.setVideodirect(direct.text());
            Element actor = dom.selectFirst("div.vodinfobox > ul > li:nth-child(3) > span");

            video.setVideoactor(actor.text());
            Element videotype = dom.selectFirst("div.vodinfobox > ul > li:nth-child(4) > span");
            List<TbType> typeList = typeMapper.selectAllByTypenameList(videotype.text());
            if (typeList != null && typeList.size() > 0) {
                TbType type = typeList.get(0);
                video.setTypeid(type.getTypeid());
            } else {
                video.setTypeid(36);
            }

            Element videoarea = dom.selectFirst("div.vodinfobox > ul > li:nth-child(5) > span");
            video.setVideoarea(videoarea.text());

            Element videolan = dom.selectFirst("div.vodinfobox > ul > li:nth-child(6) > span");
            System.out.println(videolan.text());
            video.setVideolan(videolan.text());

            Element videotime = dom.selectFirst("div.vodinfobox > ul > li:nth-child(7) > span");

            video.setVideoage(videotime.text());

            Element videolength = dom.selectFirst("div.vodinfobox > ul > li:nth-child(9) > span");

            video.setVideolength(Integer.parseInt(videolength.text()));

            Element score = dom.selectFirst("div.vodinfobox > ul > li:nth-child(13) > span");

            video.setScore(Double.parseDouble(score.text()));
            Element info = dom.selectFirst(".vodplayinfo");
            video.setVideoinfo(info.text());


            video.setLastmodifytime(updateTime);

            Elements as = dom.select("#play_1 > ul > li >  a:nth-child(2)");
            StringBuffer playurl = new StringBuffer();
            for (Element a : as) {
                playurl.append(a.text() + "\r\n");

            }
            tbVideoMapper.updateByPrimaryKey(video);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}